from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU, GoodsCategory
from goods.serializers import CategoriesListSerializer, SKUIndexSerializer, SKUHisrotySerializer, SKUSerializer


class SKUListView(ListAPIView):
    """
    sku列表数据
    """
    serializer_class = CategoriesListSerializer

    # 分页与排序
    filter_backends = (OrderingFilter,)
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        """
        获取查询集
        :return:
        """
        return SKU.objects.filter(category_id=self.kwargs["pk"])


class SKUSerchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]
    serializer_class = SKUIndexSerializer

class CategoriesView(APIView):
    """获取当前分类信息"""

    def get(self,request, pk):
        """
        1.获取前端数据
        2. 查询当前三级分类信息
        3.通过三级分类信息获取一二集分类
        4. 返回
        :param request:
        :return:
        """
        cat3 = GoodsCategory.objects.get(id=pk) # 获取三级
        cat2 = cat3.parent  # 自关联获取二级,
        cat1 = cat2.parent  # 自关联获取一级

        # 返回数据
        return Response({
            "cat1": cat1.name,
            "cat2": cat2.name,
            "cat3": cat3.name
        })


class SKUHistoryView(CreateAPIView):
    """ 保存用户历史浏览记录 """
    serializer_class = SKUHisrotySerializer
    permission_classes = [IsAuthenticated]  # 验证用户

    def get(self, request):
        """
        获取用户浏览记录
        :param request:
        :return:
        """
        user_id = request.user.id

        redis_conn = get_redis_connection('history')
        history = redis_conn.lrange("history_{}".format(user_id),0, 10)

        skus = []

        # 为了保持查询出的用户浏览的顺序一致
        for sku_id in history:
            sku = SKU.objects.get(id = sku_id)
            skus.append(sku)

        s = SKUSerializer(skus, many=True)
        return Response(s.data)